package leetCode.fourthWeek;

public class Code_87 {
  public boolean isScramble(String s1, String s2) {
    if (s1.equals(s2)) {
      return true;
    }
    int s1_ASCLL = 0;
    int s2_ASCLL = 0;

    for (int i = 0; i < s1.length(); i++) {
      s1_ASCLL += s1.charAt(i);
      s2_ASCLL += s2.charAt(i);
    }

    if (s1_ASCLL != s2_ASCLL) {
      return false;
    }

    for (int i = 1; i < s1.length(); i++) {
      String tmp1_l = s1.substring(0, i);
      String tmp1_r = s1.substring(i);
      String tmp1_l_back = s1.substring(0, s1.length() - i);
      String tmp1_r_back = s1.substring(s1.length() - i);
      String tmp2_l = s2.substring(0, i);
      String tmp2_r = s2.substring(i);
      if ((tmp1_l + tmp1_r).equals(tmp2_r + tmp2_l)) {
        return true;
      }
      if (isScramble(tmp1_l, tmp2_l) && isScramble(tmp1_r, tmp2_r)) {
        return true;
      }
      if (isScramble(tmp1_r_back, tmp2_l) && isScramble(tmp1_l_back, tmp2_r)) {
        return true;
      }
    }
    return false;
  }
}
